package service

import (
	__ "activity_srv/basic/proto"
	"activity_srv/handler/dao"
	"activity_srv/handler/models"
	"activity_srv/untils"
	"context"
	"errors"
	"strconv"
)

type Serve struct {
	__.UnimplementedActivityServer
}

// 添加发票
func (s *Serve) CreateInvoice(_ context.Context, in *__.CreateInvoiceReq) (*__.CreateInvoiceResp, error) {
	var invoice models.Invoice
	err := dao.CreateInvoice(in)
	if err != nil {
		return nil, errors.New("添加发票失败: " + err.Error())
	}

	return &__.CreateInvoiceResp{Id: int32(invoice.Id)}, nil
}

// 展示发票
func (s *Serve) ListInvoice(_ context.Context, in *__.ListInvoiceReq) (*__.ListInvoiceResp, error) {
	Invoice, err := dao.ListInvoice(in)
	if err != nil {
		return nil, errors.New("展示发票失败: " + err.Error())
	}
	return &__.ListInvoiceResp{
		List: Invoice,
	}, nil
}

// 删除发票
func (s *Serve) DelInvoice(_ context.Context, in *__.DelInvoiceReq) (*__.DelInvoiceResp, error) {
	err := dao.DelInvoice(in)
	if err != nil {
		return nil, errors.New("删除发票失败")
	}
	return &__.DelInvoiceResp{
		Message: "删除成功",
	}, nil
}

// 审核发票
func (s *Serve) AuditInvoice(_ context.Context, in *__.AuditInvoiceReq) (*__.AuditInvoiceResp, error) {
	_, err := dao.AuditInvoice(in)
	if err != nil {
		return nil, errors.New("审核发票失败")
	}
	return &__.AuditInvoiceResp{
		Message: "审核成功",
	}, nil
}

// 创建秒杀活动服务
func (s *Serve) CreateActivity(_ context.Context, in *__.CreateActivityReq) (*__.CreateActivityResp, error) {
	seckill, err := dao.CreateSeckill(in)
	if err != nil {
		return nil, errors.New("创建秒杀活动失败: " + err.Error())
	}
	return &__.CreateActivityResp{
		Id: int32(seckill.Id),
	}, nil
}

// 执行秒杀活动服务
func (s *Serve) ExecuteActivity(_ context.Context, in *__.ExecuteActivityReq) (*__.ExecuteActivityResp, error) {
	// 1. 执行秒杀逻辑
	_, order, err := dao.ExecuteActivity(in)
	if err != nil {
		return nil, err
	}

	// 2. 返回秒杀结果（订单号）
	return &__.ExecuteActivityResp{
		OrderNo: order.OrderNo,
	}, nil
}

// 完成秒杀活动（秒杀后）
func (s *Serve) FinishActivity(_ context.Context, in *__.FinishActivityReq) (*__.FinishActivityResp, error) {
	// 1. 完成秒杀活动逻辑
	activity, order, err := dao.FinishSeckillActivity(in)
	if err != nil {
		return nil, err
	}

	// 2. 生成支付URL
	pay := untils.AliPay{}
	payUrl := pay.Pay(order.OrderNo, strconv.FormatInt(int64(activity.SeckillPrice), 10))

	// 3. 返回订单号和支付URL
	return &__.FinishActivityResp{
		OrderNo: order.OrderNo,
		PayUrl:  payUrl,
	}, nil
}

func (s *Serve) StartOrderConsumer(_ context.Context, in *__.StartOrderConsumerReq) (*__.StartOrderConsumerResp, error) {
	dao.StartOrderConsumer()
	return &__.StartOrderConsumerResp{}, nil
}

// 展示秒杀列表
func (s *Serve) ListActivity(_ context.Context, in *__.ListActivityReq) (*__.ListActivityResp, error) {
	activity, err := dao.ListActivity(in)
	if err != nil {
		return nil, errors.New("展示秒杀列表失败: " + err.Error())
	}
	return &__.ListActivityResp{
		List: activity,
	}, nil
}
